package ncme.auto.framework.core.dynamicDatasource.configs;

import ncme.auto.framework.core.dynamicDatasource.entity.SqlConnectInfo;
import ncme.auto.framework.core.exceptions.AutoException;
import ncme.auto.framework.core.exceptions.ExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Primary
public class DynamicDataSourceConfig {

    @Autowired
    protected ApplicationContext applicationContext;

    @Value("${auto-framework-config.dynamic-datasource.configuration.change-source:false}")
    public boolean changeSource;

    public SqlConnectInfo getDataSourceInfo() {
        Map<String, DynamicDataSourceConfig> beansOfType = applicationContext.getBeansOfType(DynamicDataSourceConfig.class);
        if (beansOfType.size() != 1) {
            for (String beanKey : beansOfType.keySet()) {
                if (!beanKey.equals("dynamicDataSourceConfig")) {
                    DynamicDataSourceConfig dynamicDataSourceConfig = beansOfType.get(beanKey);
                    return dynamicDataSourceConfig.getDataSourceInfo();
                }
            }
        }
        throw new AutoException(ExceptionEnum.JDBC, "需重写DynamicDataSourceConfig的getDataSourceInfo()方法，返回正确的数据库连接信息");
    }

}
